import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

/**
 *  避免重复路由，引发的错误报警
 */
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
	{
		path: '/',
		name: 'home',
		component: () => import( /* webpackChunkName: "home" */ '../views/HomeView.vue')
	},
	{
		path: '/login',
		name: 'login',
		component: () => import( /* webpackChunkName: "login" */ '../views/LoginView.vue')
	},
	{
		path: '/admin',
		name: 'admin',
		component: () => import( /* webpackChunkName: "admin" */ '../views/admin/index.vue'),
		children: [
			{
				path: 'subjects',
				name: 'subjects',
				component: () => import( /* webpackChunkName: "subjects" */ '../views/admin/subjectList.vue'),
			},
			{
				path: 'users',
				name: 'users',
				component: () => import( /* webpackChunkName: "users" */ '../views/admin/userList.vue'),
			}
		]
	}
]

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
})

router.beforeEach(function(to, from, next) {
	if(to.path.startsWith('/login')) {
		next() //登录页直接放行
	} else {
		let user = localStorage.getItem('loginUser')
		if(!user || user == 'undefined') {
			next('/login') //没有登录用户，转向登录
		} else {
			let loginUser = JSON.parse(user)
			if (to.path.startsWith('/admin')) { 
				//后台页面必须是管理员才放行
				if(loginUser.is_admin == 1) next()
				//否则转向首页
				else next('/')
			} else {
				next(); //首页直接放行
			}
		}
	}
});


export default router
